//
//  WiiAddTagsViewController.m
//  iFeller
//
//  Created by Wii on 15/12/18.
//  Copyright © 2015年 Wii. All rights reserved.
//

#import "WiiAddTagsViewController.h"
#import "WiiAddTagsCollectionViewCell.h"
#define Identifier_CELL @"WiiChoseRepeatCell"
#define Identifier_header @"WiiChoseRepeatCellHeader"

typedef NS_ENUM (NSInteger,WiiCloseTagsAt){
    WiiCloseTagsAtAdd = 100,
    WiiCloseTagsAtDel    ,
    WiiCloseTagsAtCancel,
    WiiCloseTagsAtClose
};
@interface WiiAddTagsViewController () <UIViewControllerTransitioningDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UITextFieldDelegate>
@property (nonatomic , strong) UICollectionView *mainCollectionView;
@property (nonatomic , strong) NSMutableArray *dataSource;
@property (nonatomic , strong) UIView *topView;
@property (nonatomic , strong) UIView *bottomview;
@property (nonatomic , strong) UILabel *topLabel;
@property (nonatomic , strong) UIButton *closeButton;
@property (nonatomic , strong) UIButton *cancelButton;
@property (nonatomic , strong) UIButton *addButton;
@property (nonatomic , strong) UIButton *delButton;
@property (nonatomic , strong) NSMutableArray *TagsArray;
@property (nonatomic , strong) NSString *tags;
@property (nonatomic , strong) NSMutableArray *choseTags;
@property (nonatomic , strong) UILongPressGestureRecognizer *longPress;
@property (nonatomic , strong) UIAlertController *addTagsAlert;
@property (nonatomic , strong) WiiAddTagsCollectionViewCell *cell;
@end

@implementation WiiAddTagsViewController

- (instancetype)init{
    self = [super init];
    if (self) {
        self.TagsArray = [NSMutableArray array];
        self.choseTags = [NSMutableArray array];
        self.transitioningDelegate = self;
        self.modalTransitionStyle = UIModalPresentationCustom;
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//    [user setObject:@[@"工作",@"学习",@"裸奔"] forKey:@"tags"];
//    [user synchronize];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUserInterface];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setObject:self.dataSource forKey:@"tags"];
    [user synchronize];
}
#pragma mark -initUserInterface
- (void)initUserInterface{
    self.view.backgroundColor = [UIColor clearColor];
    self.choseTags = [NSMutableArray arrayWithArray:[self.beforeTags componentsSeparatedByString:@"，"]];
    
    self.dataSource = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"tags"]];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake((SCREEN_WIDTH - 40 ) / 4, 50);
    flowLayout.minimumLineSpacing = 1;
    flowLayout.minimumInteritemSpacing = 5;
    
    self.mainCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(10, 40, SCREEN_WIDTH - 20, SCREEN_HEIGHT / 2 - 80) collectionViewLayout:flowLayout];

    self.mainCollectionView.delegate = self;
    self.mainCollectionView.dataSource = self;
    
    [self.mainCollectionView registerClass:[WiiAddTagsCollectionViewCell class] forCellWithReuseIdentifier:Identifier_CELL];
    self.mainCollectionView.backgroundColor = [UIColor clearColor];
    
    [self.view addSubview:self.topView];
    [self.topView addSubview:self.addButton];
//    [self.topView addSubview:self.delButton];
    [self.view addSubview:self.mainCollectionView];
    [self.view addSubview:self.bottomview];
    [self.bottomview addSubview:self.closeButton];
    [self.bottomview addSubview:self.cancelButton];
    
    self.longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longTap:)];
}

#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    WiiAddTagsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:Identifier_CELL forIndexPath:indexPath];
    
    [cell.tagsButton addTarget:self action:@selector(tagsButtonHandleEvent:) forControlEvents:UIControlEventTouchUpInside];
    [cell.delButton addTarget:self action:@selector(tagsDelButtonHandleEvent:) forControlEvents:UIControlEventTouchUpInside];
    [cell.tagsButton setTitle:self.dataSource[indexPath.row] forState:UIControlStateNormal];
    if ([self.choseTags containsObject:self.dataSource[indexPath.row]]) {
            cell.tagsButton.selected = YES;
        [self.TagsArray addObject:self.dataSource[indexPath.row]];
        cell.tagsButton.backgroundColor = [UIColor greenColor];
        [cell.tagsButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
    self.cell = cell;
    return cell;
}

#pragma mark - UIViewControllerTransitioningDelegate

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
    return [WiiKit transitionWithTransitionType:WiiPresentTransitionPresent];
}
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
    return [WiiKit transitionWithTransitionType:WiiPresentTransitionDismiss];
}

#pragma mark - 按钮点击事件 handleEvet
- (void)handleEvet:(UIButton *)sender{
    switch (sender.tag) {
        case WiiCloseTagsAtCancel:{
            [self dismissViewControllerAnimated:YES completion:nil];
        }
            break;
        case WiiCloseTagsAtClose:{
            self.tags = [self.TagsArray componentsJoinedByString:@"，"];
            self.block(self.tags);
            [self dismissViewControllerAnimated:YES completion:nil];
        }
            break;
        case WiiCloseTagsAtAdd:{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"增加" message:@"请输入标签名称" preferredStyle:UIAlertControllerStyleAlert];
            [alertController addTextFieldWithConfigurationHandler:nil];
            UIAlertAction *AddAction = [UIAlertAction actionWithTitle:@"增加标签" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                // 获取 输入内容
                NSString *inputText = alertController.textFields[0].text;
                [self.dataSource insertObject:inputText atIndex:0];
//                [self.mainCollectionView reloadData];
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                [self.mainCollectionView insertItemsAtIndexPaths:@[indexPath]];
            }];
            UIAlertAction *canceAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
            
            [alertController addAction:AddAction];
            [alertController addAction:canceAction];
            self.addTagsAlert = alertController;
            self.addTagsAlert.textFields[0].delegate = self;
            [self presentViewController:self.addTagsAlert animated:YES completion:nil];
        }
            break;
        default:
            break;
    }
}

#pragma mark - uitextfiled字数限制
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == self.addTagsAlert.textFields[0]) {
        if (range.location >= 4) {//限制只允许输入11位
            return NO;
        }
    }
    return YES;
}
#pragma mark - 便签点击事件
- (void)tagsButtonHandleEvent:(UIButton *)sender{
    sender.selected = !sender.selected;
    NSLog(@"tags:---------->%ld",sender.tag);
    if (sender.selected) {
        sender.backgroundColor = [UIColor greenColor];
        [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        [self.TagsArray addObject:sender.titleLabel.text];
        NSLog(@"tags:---------->%@",self.TagsArray);
        return;
    } else{
        sender.backgroundColor = [UIColor whiteColor];
        [sender setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self.TagsArray removeObject:sender.titleLabel.text];
        NSLog(@"tags romove:---------->%@",self.TagsArray);
    }
}
- (void)tagsDelButtonHandleEvent:(UIButton *)sender{
    UIView *v = [sender superview];//获取父类view
    WiiAddTagsCollectionViewCell *cell = (WiiAddTagsCollectionViewCell *)[v superview];//获取cell
    
    NSIndexPath *indexPath = [self.mainCollectionView indexPathForCell:cell];//获取cell对应的indexpath;
    NSLog(@"indexPath:---------->%@",indexPath);
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示！" message:@"确定要删除该标签吗？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            [self.mainCollectionView deleteItemsAtIndexPaths:@[indexPath]];
            [self.dataSource removeObjectAtIndex:indexPath.row];
            [self.mainCollectionView reloadData];
        }];
        UIAlertAction *cacelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cacelAction];
        [alert addAction:sureAction];
        [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - tap
- (void)longTap:(UILongPressGestureRecognizer *)tap{
    CGPoint point = [tap locationInView:self.cell.tagsButton];
    NSIndexPath *indexPath = [self.mainCollectionView indexPathForItemAtPoint:point];
    NSLog(@"%@==%ld==%ld",indexPath, indexPath.section, indexPath.row);
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示！" message:@"确定要删除该标签吗？" preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        NSLog(@"id:---------->%ld",i);
//    }];
//    UIAlertAction *cacelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//    [alert addAction:cacelAction];
//    [alert addAction:sureAction];
//    [self presentViewController:alert animated:YES completion:nil];
//    self.cell.delButton.hidden = NO;
}
#pragma mark - Block回调 (void)respondsButtonWithTags:(TagsBlock)tagsBlock;
- (void)respondsButtonWithRepeat:(TagsBlock)tagsBlock{
    self.block = tagsBlock;
}
#pragma mark - setter/getter
- (UIView *)topView{
    if (!_topView) {
        _topView = [[UIView alloc]initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH - 20, 30)];
    }
    return _topView;
}
- (UIView *)bottomview{
    if (!_bottomview) {
        _bottomview = [[UIView alloc]initWithFrame:CGRectMake(10, SCREEN_HEIGHT / 2 - 30, SCREEN_WIDTH - 20, 30)];
    }
    return _bottomview;
}
- (UIButton *)addButton{
    if (!_addButton) {
        _addButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [_addButton setBackgroundImage:[UIImage imageNamed:@"Tags_add"] forState:UIControlStateNormal];
        _addButton.frame = CGRectMake(0, 0, 30, 30);
        _addButton.center = CGPointMake((SCREEN_WIDTH - 20) / 2, 15);
        _addButton.tag = 100;
        [_addButton addTarget:self action:@selector(handleEvet:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addButton;
}
- (UIButton *)delButton{
    if (!_delButton) {
        _delButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [_delButton setBackgroundImage:[UIImage imageNamed:@"Add"] forState:UIControlStateNormal];
        _delButton.frame = CGRectMake(0, 0, 30, 30);
        _delButton.center = CGPointMake(SCREEN_WIDTH - SCREEN_WIDTH / 3 - 20, 15);
        _delButton.tag = 101;
        [_delButton addTarget:self action:@selector(handleEvet:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _delButton;
}
- (UIButton *)closeButton{
    if (!_closeButton) {
        _closeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        _closeButton.frame = CGRectMake(0, 0, 30, 30);
        _closeButton.center = CGPointMake(SCREEN_WIDTH - SCREEN_WIDTH / 3 - 20, 15);
        [_closeButton setBackgroundImage:[UIImage imageNamed:@"OK"] forState:UIControlStateNormal];
        _closeButton.tag = 103;
        [_closeButton addTarget:self action:@selector(handleEvet:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeButton;
}
- (UIButton *)cancelButton{
    if (!_cancelButton) {
        _cancelButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        _cancelButton.frame = CGRectMake(0, 0, 30, 30);
        _cancelButton.center = CGPointMake(SCREEN_WIDTH / 3, 15);
        [_cancelButton setBackgroundImage:[UIImage imageNamed:@"not"] forState:UIControlStateNormal];
        _cancelButton.tag = 102;
        [_cancelButton addTarget:self action:@selector(handleEvet:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelButton;
}


@end
